using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace CalmNine.Framework
{
    public class ObservableList<T> : Collection<T> where T : class, INotifyPropertyChanged
    {
        public event Action<T> OnItemAdded;
        public event Action<T> OnItemRemoved;
        public event Action<T> OnItemChanged;

        protected override void InsertItem(int index, T item)
        {
            base.InsertItem(index, item);
            item.PropertyChanged += Item_PropertyChanged;
            OnItemAdded?.Invoke(item);
        }

        protected override void RemoveItem(int index)
        {
            T item = this[index];
            item.PropertyChanged -= Item_PropertyChanged;
            base.RemoveItem(index);
            OnItemRemoved?.Invoke(item);
        }

        protected override void SetItem(int index, T item)
        {
            T oldItem = this[index];
            oldItem.PropertyChanged -= Item_PropertyChanged;
            base.SetItem(index, item);
            item.PropertyChanged += Item_PropertyChanged;
            OnItemRemoved?.Invoke(oldItem);
            OnItemAdded?.Invoke(item);
        }

        public void NotifyItemChanged(T item)
        {
            if (Contains(item))
            {
                OnItemChanged?.Invoke(item);
            }
        }

        public void Clear(bool notifyItemRemoved = true)
        {
            if (notifyItemRemoved)
            {
                List<T> items = new List<T>(this);
                foreach (T item in items)
                {
                    item.PropertyChanged -= Item_PropertyChanged;
                }
                base.Clear();
                foreach (T item in items)
                {
                    OnItemRemoved?.Invoke(item);
                }
            }
            else
            {
                foreach (T item in this)
                {
                    item.PropertyChanged -= Item_PropertyChanged;
                }
                base.Clear();
            }
        }

        private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            OnItemChanged?.Invoke(sender as T);
        }
    }
}